<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 添加分类按钮 -->
      <el-row>
        <el-col>
          <el-button type="primary"
                     @click="addCateDialog">添加分类</el-button>
        </el-col>
      </el-row>
      <!-- table栏区域 -->
      <tree-table :data="cateData"
                  :columns="columns"
                  :selection-type="false"
                  :expand-type="false"
                  show-index
                  index-text="#"
                  border
                  :show-row-hover="false"
                  class="tree-table">
        <template slot="isok"
                  slot-scope="scope">
          <i class="el-icon-success"
             v-if="scope.row.cat_deleted = true"></i>
          <i class="el-icon-error"
             v-else-if="scope.row.cat_deleted = false"></i>
        </template>
        <template slot="level"
                  slot-scope="scope">
          <el-tag v-if="scope.row.cat_level === 0">一级</el-tag>
          <el-tag type="success"
                  v-else-if="scope.row.cat_level === 1">二级</el-tag>
          <el-tag type="warning"
                  v-else-if="scope.row.cat_level === 2">三级</el-tag>
        </template>
        <template slot="handle"
                  slot-scope="scope">
          <el-button type="primary"
                     size="mini"
                     icon="el-icon-edit"
                     @click="editCate(scope.row)">编辑</el-button>
          <el-button type="danger"
                     size="mini"
                     icon="el-icon-delete"
                     @click="deleteCate(scope.row.cat_id)">删除</el-button>
        </template>
      </tree-table>
      <!-- 分页功能区域 -->
      <el-pagination @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"
                     :current-page="queryInfo.pagenum"
                     :page-sizes="[5, 8, 10, 15]"
                     :page-size="5"
                     layout=" total,sizes, prev, pager, next, jumper"
                     :total="total">
      </el-pagination>
    </el-card>
    <!-- 添加分类对话框 -->
    <el-dialog title="添加分类"
               :visible.sync="addCateDialogVisible"
               width="50%"
               @close="addCateDialogClosed">

      <el-form :model="addCateForm"
               :rules="addCateRules"
               ref="addCateRefs"
               label-width="100px">
        <el-form-item label="分类名称"
                      prop="cat_name">
          <el-input v-model="addCateForm.cat_name"></el-input>
        </el-form-item>

        <el-form-item label="父级分类">
          <el-cascader :props="cascaderProps"
                       :options="parentCateList"
                       v-model="activeParentList"
                       @change="parentCateChanged"
                       clearable
                       change-on-select>
          </el-cascader>
        </el-form-item>
      </el-form>

      <span slot="footer"
            class="dialog-footer">
        <el-button @click="addCateDialogVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="addCate">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑对话框 -->
    <el-dialog title="编辑分类"
               :visible.sync="editDialogVisible"
               width="50%"
               @close="editCateClose">

      <el-form :model="editInfo"
               ref="editRef"
               label-width="100px"
               :rules="addCateRules">
        <el-form-item label="分类名称"
                      prop="cat_name">
          <el-input v-model="editInfo.cat_name"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer"
            class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="editCatey">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data () {
    return {
      queryInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5
      },
      // 定义列规则
      columns: [{
        label: '分类名称',
        prop: 'cat_name',
        width: '380px'
      }, {
        label: '是否有效',
        prop: 'cat_deleted',
        width: '380px',
        type: 'template',
        template: 'isok'
      }, {
        label: '排序',
        prop: 'cat_level',
        width: '380px',
        type: 'template',
        template: 'level'
      }, {
        label: '操作',
        width: '380px',
        type: 'template',
        template: 'handle'
      }],
      total: 0,
      cateData: [],
      // 控制添加分类对话框的显示隐藏
      addCateDialogVisible: false,
      // 添加分类
      addCateForm: {},
      // 添加分类验证规则
      addCateRules: {
        cat_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' },
          { min: 2, max: 6, message: '长度在 2 到 6 个字符', trigger: 'blur' }
        ]
      },
      // 父级分类列表
      parentCateList: [],
      // 级联选择器的配置对象
      cascaderProps: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      activeParentList: [],
      // 控制编辑对话框的显示隐藏
      editDialogVisible: false,
      editInfo: {
        cat_name: ''
      },
      // 需要编辑分类的ID
      editCateID: ''
    }
  },
  methods: {
    // 获取分类列表
    async getCateForm () {
      const { data: res } = await this.$http.get('categories', { params: this.queryInfo })
      if (res.meta.status !== 200) return this.$message.error('获取列表失败')
      this.cateData = res.data.result
      this.total = res.data.total
    },
    // // 监听页数的改变
    handleSizeChange (pagesize) {
      this.queryInfo.pagesize = pagesize
      this.getCateForm()
    },
    // 监听当前页的改变
    handleCurrentChange (pagenum) {
      this.queryInfo.pagenum = pagenum
      this.getCateForm()
    },
    // 点击分类按钮
    addCateDialog () {
      this.getParentCateList()
      this.addCateDialogVisible = true
    },
    // 获取父级分类列表
    async getParentCateList () {
      const { data: res } = await this.$http.get('categories', {
        params: { type: 2 }
      })
      if (res.meta.status !== 200) return this.$message.error('获取父级列表失败')
      this.parentCateList = res.data
    },
    // 监听父级分类变动
    parentCateChanged () {
      if (this.activeParentList.length > 0) {
        this.addCateForm.cat_pid = this.activeParentList[this.activeParentList.length - 1]
        this.addCateForm.cat_level = this.activeParentList.length
      } else {
        this.addCateForm.cat_pid = 0
        this.addCateForm.cat_level = 0
      }
    },
    // 监听对话框的关闭事件, 重置表单数据
    addCateDialogClosed () {
      this.addCateForm.cat_name = ''
      this.addCateForm.cat_pid = 0
      this.addCateForm.cat_level = 0
      this.activeParentList = []
    },
    // 确认添加分类
    addCate () {
      this.$refs.addCateRefs.validate(async valid => {
        if (!valid) return null
        const { data: res } = await this.$http.post('categories', this.addCateForm)
        if (res.meta.status !== 201) return this.$message.error('添加分类失败')
        this.$message.success('添加分类成功')
        this.getCateForm()
        this.addCateDialogVisible = false
      })
    },
    // 点击编辑按钮
    editCate (cate) {
      this.editCateID = cate.cat_id
      this.editDialogVisible = true
    },
    // 监听编辑对话框的关闭事件
    editCateClose () {
      this.$refs.editRef.resetFields()
      this.editInfo.cat_name = ''
    },
    // 确任编辑分类名称
    editCatey () {
      this.$refs.editRef.validate(async valid => {
        if (!valid) return null
        const { data: res } = await this.$http.put('categories/' + this.editCateID, this.editInfo)
        if (res.meta.status !== 200) return this.$message.error('添加分类失败')
        this.$message.success('添加分类成功')
        this.getCateForm()
        this.editDialogVisible = false
      })
    },
    // 删除分类
    async deleteCate (ID) {
      const res = await this.$confirm('此操作将永久删除该分类, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (res === 'cancel') return this.$message.info('已经为您取消操作')
      if (res === 'confirm') {
        const { data: res } = await this.$http.delete('categories/' + ID)
        if (res.meta.status !== 200) return this.$message.error('删除分类失败')
        this.$message.success('删除分类成功')
        this.getCateForm()
      }
    }

  },
  created () {
    this.getCateForm()
  }
}
</script>
<style lang="less" scoped>
.el-icon-success {
  color: green;
}
.el-icon-error {
  color: red;
}
.tree-table {
  margin: 20px 0;
}
.el-cascader {
  width: 100%;
}
</style>
